<template>
  <el-dialog :title="title" v-model="visible" append-to-body class="dialog-sm" @close="close">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :validate-on-rule-change="false"
      label-width="80px"
      v-loading="loading">
      <el-form-item label="参数名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入参数名称" maxlength="64" />
      </el-form-item>
      <el-form-item label="参数键名" prop="config_key">
        <el-input
          v-model="form.config_key"
          placeholder="请输入参数键名"
          maxlength="64"
          :disabled="rowData && rowData.is_sys === '1'" />
      </el-form-item>
      <el-form-item label="所属分组" prop="groups">
        <el-select v-model="form.groups" placeholder="请选择参数分组">
          <el-option v-for="(item, index) in groupList" :key="index" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="参数类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择参数类型">
              <el-option label="文本" value="text" />
              <el-option label="文件" value="file" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="list_sort">
            <el-input-number v-model="form.list_sort" controls-position="right" :min="0" class="w-full" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="参数值" prop="textValue" v-if="form.type === 'file'">
        <file-upload over-hide-upload :default-list="defaultFile" v-model="form.fileValue" />
      </el-form-item>
      <el-form-item label="参数值" prop="textValue" v-else>
        <el-input v-model="form.textValue" type="textarea" :autosize="{ minRows: 2 }" placeholder="请输入参数值" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="250" />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button class="medium" type="primary" :loading="submitting" :disabled="loading" @click="handleSubmit"
        >确 定</el-button
      >
      <el-button class="medium" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script setup name="ConfigForm">
  import { addConfigApi, editConfigApi, infoConfigApi } from '@/api/system/config'

  const props = defineProps({ row: Object, moduleName: String })
  const visible = defineModel()
  const { proxy } = getCurrentInstance()
  const formRef = useTemplateRef('formRef')

  const form = ref({
    name: undefined,
    config_key: undefined,
    type: 'text',
    list_sort: 10,
    groups: undefined,
    textValue: undefined,
    fileValue: undefined,
    remark: undefined
  })
  const rules = computed(() => {
    const rules = {
      name: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
      config_key: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
      type: [{ required: true, message: '参数类型不能为空', trigger: 'blur' }],
      list_sort: [{ required: true, message: '参数排序不能为空', trigger: 'blur' }]
    }
    formRef.value?.clearValidate()
    if (form.value.type === 'file') {
      return { ...rules, fileValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }] }
    } else {
      return { ...rules, textValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }] }
    }
  })

  // 初始化加载
  const title = ref('')
  const loading = ref(false)
  onMounted(async () => {
    loading.value = true
    form.value.id = props.row?.id || undefined
    if (form.value.id) {
      title.value = '编辑' + props.moduleName
      await getRowData()
    } else {
      title.value = '添加' + props.moduleName
    }
    loading.value = false
  })

  // 获取分组数据
  const groupOption = proxy.useConfig('sys.conf.group')
  const groupList = computed(() => {
    return groupOption.value?.split(';') || []
  })

  // 获取编辑时的信息
  const rowData = ref(null)
  const defaultFile = ref('')
  async function getRowData() {
    try {
      const { info } = await infoConfigApi(form.value.id)
      form.value = proxy.dataToForm(form.value, info)
      if (form.value.type === 'file') {
        form.value.fileValue = info?.value || ''
        defaultFile.value = info?.value || ''
      } else {
        form.value.textValue = info?.value || ''
      }
      rowData.value = info || {}
    } catch (error) {
      close()
    }
  }

  // 提交保存
  const submitting = ref(false)
  async function handleSubmit() {
    try {
      const valid = await formRef.value.validate()
      if (!valid) return
    } catch (error) {
      return
    }
    if (submitting.value) return
    submitting.value = true
    let data = proxy.deepClone(form.value)
    delete data.textValue
    delete data.fileValue
    if (form.value.type === 'text') {
      data.value = form.value.textValue
    } else if (form.value.type === 'file') {
      data.value = form.value.fileValue
    }
    try {
      await proxy.$modal.confirm('确定提交表单数据？')
      if (form.value.id) {
        await editConfigApi(data)
      } else {
        await addConfigApi(data)
      }
      close(true, '操作成功')
    } catch (e) {
      submitting.value = false
    }
  }

  // 关闭弹窗
  const emit = defineEmits(['submit'])
  function close(submit = false, msg = '') {
    if (submit === true) emit('submit')
    if (msg) submit === true ? proxy.$modal.msgSuccess(msg) : proxy.$modal.msgError(msg)
    visible.value = false
  }
</script>
